# -*- coding: utf-8 -*-
# @Time : 2022/6/22 22:12
# @Author : cheney
# @File : ultrasonicDao.py
# @Software: PyCharm
# @Site: www.cheney.cc
"""
    超声波模块，一般和舵机模块一起使用
"""

import RPi.GPIO as GPIO
import time
import sys


class ultrasonicDao:
    BtnPin = 19
    Gpin = 5
    Rpin = 6

    TRIG = 20
    ECHO = 21

    GPIO.setwarnings(False)
    GPIO.setmode(GPIO.BCM)
    GPIO.setup(TRIG, GPIO.OUT)
    GPIO.setup(ECHO, GPIO.IN)

    # def __init__(self):

    #     self.keysacn()

    # def keysacn(self):
    #     val = GPIO.input(self.BtnPin)
    #     while not GPIO.input(self.BtnPin):
    #         val = GPIO.input(self.BtnPin)
    #     while GPIO.input(self.BtnPin):
    #         time.sleep(0.01)
    #         val = GPIO.input(self.BtnPin)
    #         if val:
    #             GPIO.output(self.Rpin, 1)
    #             while not GPIO.input(self.BtnPin):
    #                 GPIO.output(self.Rpin, 0)
    #         else:
    #             GPIO.output(self.Rpin, 0)

    def get_distance(self) -> float:
        """
        通过超声波模块获取距离
        :return:
        """
        GPIO.output(self.TRIG, 0)
        time.sleep(0.000002)

        GPIO.output(self.TRIG, 1)
        time.sleep(0.00001)
        GPIO.output(self.TRIG, 0)

        while GPIO.input(self.ECHO) == 0:
            a = 0
        time1 = time.time()
        while GPIO.input(self.ECHO) == 1:
            a = 1
        time2 = time.time()

        during = time2 - time1
        return during * 340 / 2 * 100


if __name__ == '__main__':
    ult_con = ultrasonicDao()
    while True:
        print("distance： ", ult_con.get_distance(),"\n")
        for i in range(5):
            print("\rscan after", 4 - i, "seconds", end="")
            time.sleep(1)